package org.ainlolcat.ainscience.statistics.handlers.hitran;

import org.ainlolcat.ainscience.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ainlolcat
 *         Date: 5/1/13
 */
public class LineLoader{
    //@TODO add soft reference
    private static LineLoader instance;
    private String a_X_0_0 = "a_X_0_0.dat";
	private String b_X_0_0 = "b_X_0_0.dat";
    private List<SpectrLine> Ax;
    private List<SpectrLine> Bx;

    private LineLoader(){}

    public static LineLoader getInstance(){
        if (instance == null){
            instance =new LineLoader();
        }
        return instance;
    }

    private void loadAx() throws IOException {
        Ax = new ArrayList<SpectrLine>();
		File f = new File(a_X_0_0);
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
        while(br.ready()){
		    String line = br.readLine();
			String[] lexs = line.split("\t");
			try{
				tools.parseDouble(lexs[0]);
            }
			catch(Exception ex){
                System.out.println(line);
                //ex.printStackTrace();
				continue;
            }
			SpectrLine tempRaw = new SpectrLine();
			tempRaw.fill(lexs);
            Ax.add(tempRaw);
        }
		fr.close();
    }

    private void loadBx() throws IOException {
        Bx = new ArrayList<SpectrLine>();
		File f = new File(b_X_0_0);
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
        while(br.ready()){
		    String line = br.readLine();
			String[] lexs = line.split("\t");
			try{
				tools.parseDouble(lexs[0]);
            }
			catch(Exception ex){
                System.out.println(line);
				continue;
            }
			SpectrLine tempRaw = new SpectrLine();
			tempRaw.fill(lexs);
            Bx.add(tempRaw);
        }
		fr.close();
    }

    public List<SpectrLine> getAxLines() throws IOException {
        if (Ax == null){
            loadAx();
        }
        return Ax;
    }

    public List<SpectrLine> getBxLines() throws IOException {
        if (Bx == null){
            loadBx();
        }
        return Bx;
    }
}
